<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">安全知识库</div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-col :span="5">
            <el-form-item label="文档名称" prop="documentName">
              <el-input
                v-model="queryParams.documentName"
                placeholder="请输入文档名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary"  @click="handleQuery">搜索</el-button>
              <el-button  @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['base:securityRep:add']">新增</el-button>
        </div>
        <div class="ct-table">
          <elTables
            :table-data="tableData"
            :columns="tableColumns"
            :currentPage="queryParams.pageNum"
            :totalLength="total"
            :handle-current-change="handleCurrentChange"
            isPagin
            :curHeight="tableHeight"
          />
        </div>
      </div>
      </div>
    <!-- 添加或修改安全知识库对话框 -->
    <el-dialog :title="title" :visible.sync="open"  append-to-body @close="cancel" class="dialog-form">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-col :span="24">
          <el-form-item label="文档名称" prop="documentName">
            <el-input v-model="form.documentName" placeholder="请输入文档名称" :readonly="!isEdit" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容简介" prop="contentIntroduction">
            <el-input v-model="form.contentIntroduction" type="textarea" rows="3" placeholder="请输入内容内容简介" :readonly="!isEdit"
              :disabled="!isEdit" maxlength="300" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传文件" prop="fileUrl">
            <elUploads :disabled="!isEdit" :ref="'upload'" :action="action" :auto-upload="true" :limit="5"
              :fileList="fileList" :remove-file="removeFile" :accept="'.jpg,.png'" :success-fun="success"
              :readonly="!isEdit" tip="提示：仅允许上传.jpg,.png格式文件，且不能超过100M！"></elUploads>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="isEdit">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
  const defaultQueryParams = {
    pageNum: 1,
    pageSize: 10,
  };
import { pageSecurityRep, getSecurityRep, delSecurityRep, addSecurityRep, updateSecurityRep} from "@/api/base/securityRep";
      
export default {
  name: "SecurityRep",
  data() {
    return {
      tableHeight:0,
      isEdit:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,
        documentName: null,
        factoryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        documentName: [
          { required: true, message: "文档名称不能为空", trigger: "blur" }
        ],
        contentIntroduction: [
          { required: true, message: "内容简介不能为空", trigger: "blur" }
        ],
        fileUrl: [
          { required: true, message: "上传图片不能为空",trigger: "blur" }
        ],
      },
      tableColumns: [
      { key:"documentName",title:"文档名称"},
      { key:"contentIntroduction",title:"内容简介"},
      { key:"createTime",title:"创建时间"},
      { key:"updateTime",title:"修改时间"},
      {
        title: "操作",
        align: "center",
        fixed:'right',
        width: 200,
        render: (h, params) => {
          return h("div", [
            h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:securityRep:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row,2)
                    },
                  },
                },
                "查看"
            ),
          h(
              "el-button",
              {
                  props: {
                      type: "text",
                      size: "small",
                  },
                  directives: [
                      {
                          name: "hasPermi",
                          value: ["base:securityRep:edit"],
                      },
                  ],
                  on: {
                      click: () => {
                          this.handleUpdate(params.row,1);
                      },
                  },
              },
              "编辑"
          ),
            h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:securityRep:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row)
                    },
                  },
                },
                "删除"
            ),
          ]);
        }
      }],
      fileList: [],
      action: process.env.VUE_APP_BASE_API + "/common/upload"
    };
  },
  created() {
    this.getPage();
  },
  mounted(){
    this.$nextTick(() => {
      this.getTableHeight();
    })
  },
  methods: {
    getTableHeight(){
      let height=document.getElementsByClassName('ct-table')[0].clientHeight;
      this.tableHeight= height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询安全知识库列表 */
    getPage() {
      this.loading = true;
      pageSecurityRep(this.queryParams).then(response => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList=[];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        documentName: null,
        contentIntroduction: null,
        fileUrl: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit= true;
      this.title = "新增安全知识库";
    },
    /** 修改按钮操作 */
    handleUpdate(row,type) {
      if(type==1){
        this.isEdit=true;
        this.title = "编辑安全知识库";
      }else{
        this.isEdit=false;
        this.title = "查看安全知识库";
      }
      this.reset();
      const id = row.id || this.ids
      getSecurityRep(id).then(response => {
        this.form = response.data;
        this.fileList=JSON.parse(this.form.fileUrl);
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 对fileUrl处理
      if(this.fileList&&this.fileList.length>0){
        let ls=this.fileList.map(_ => {
          return {
            url:_?.response?.fileName??_.url,
            name:_?.response?.oldFileName??_.name,
          }
        })
        this.form.fileUrl=JSON.stringify(ls);
      }else{
        this.form.fileUrl='';
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSecurityRep(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getPage();
            });
          } else {
            addSecurityRep(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
            let data
            if(Array.isArray(ids)){
              data=ids
            }else{
              data=[ids]
            }
          return delSecurityRep(data);
        }).then(() => {
          this.getPage();
          this.msgSuccess("删除成功");
        })
    },
    handleExceed(files, fileList) {
      this.$message.error(`只允许上传单个文件`);
    },
    // 移除文件
    removeFile(file, fileList) {
      this.fileList = fileList;
    },
    // 上传文件
    success(response, file, fileList) {
      if (response.code == 200) {
        this.fileList=fileList;
        this.$refs.form.clearValidate("fileUrl");
        this.$message.success("上传成功！");
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>